package risk.control.project.api;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import risk.control.project.config.constant.FilePath;
import risk.control.project.service.AuthCodeService;
import risk.control.project.service.TakeRecordService;
import risk.control.project.utils.response.ResponseUtils;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static risk.control.project.utils.vaild.DateTimeValidator.isValidDateTime;
import static risk.control.project.utils.vaild.DateTimeValidator.isValidTimeRange;


@RestController
public class MAIN_000_001_003 {
    private static final Logger logger = LoggerFactory.getLogger(MAIN_000_001_003.class);

    private final AuthCodeService authCodeService;
    private final TakeRecordService takeRecordService;

    public MAIN_000_001_003(AuthCodeService authCodeService, TakeRecordService takeRecordService) {
        this.authCodeService = authCodeService;
        this.takeRecordService = takeRecordService;
    }

    //导出取现记录
    @GetMapping("main/000_001_003")
    public ResponseEntity<?> downloadFile(@RequestParam Map<String, String> params) {
        try {
            //参数
            String authCode = params.get("authCode");
            String startTime = params.get("startTime");
            String endTime = params.get("endTime");
            //校验请求合法性
            HashMap<String, String> map = authCodeService.verifyAuthCode(authCode);
            String state = map.get("state");
            if (!state.equals("000")) {
                String msg = map.get("msg");
                String data = ResponseUtils.generateFail(msg);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            if (!isValidDateTime(startTime)) {
                String data = ResponseUtils.generateFail("请输入合法的开始时间");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            if (!isValidDateTime(endTime)) {
                String data = ResponseUtils.generateFail("请输入合法的结束时间");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            if (!isValidTimeRange(startTime, endTime)) {
                String data = ResponseUtils.generateFail("开始时间不晚于结束时间");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            //开始写入文件
            HashMap<String, String> respMap = takeRecordService.fullQueryRecord(startTime, endTime);
            if (!respMap.get("state").equals("000")) {
                String msg = respMap.get("msg");
                String data = ResponseUtils.generateFail(msg);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            //读取文件
            String s = respMap.get("filePath");
            Path filePath = Paths.get(s);
            Resource resource = new UrlResource(filePath.toUri());
            if (!resource.exists()) {
                // 更详细的错误信息
                String data = ResponseUtils.generateFail("文件不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            // 检查可读性
            if (!resource.isReadable()) {
                String data = ResponseUtils.generateFail("文件不可读");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
            }
            return ResponseEntity.ok()//
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)//
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")//
                    .body(resource);//
        } catch (Exception e) {
            String data = ResponseUtils.generateFail("文件下载失败");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(data);
        }
    }


}
